/**
 * Created by moc on 2016/4/17.
 */
var express = require('express');
var router = express.Router();
var xml2js = require('xml2js');
var tmpl = require('tmpl');
var request = require('request');

var appID = "wx9f43b4a5b2ff7e1b";
var appSecret = "7112700707f89d4871279f53f937c521";
var accesstoken;


//************** WebSocketServer
var WebSocketServer = require('ws').Server
    , wss = new WebSocketServer({port: 10001});

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('web socket received: %s', message);
    });
});
wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
        client.send(data);
    })
};

//**************

router.get('/', function (req, res, next) {
    console.log("wx")
    var signature = req.query.signature
    var echostr = req.query.echostr
    res.end(echostr)
})

router.get('/chat', function (req, res, next) {
    res.render('wxchat');
})

router.post('/', function (req, res, next) {
    var postdata = ''
    req.addListener('data', function (chunk) {
        postdata += chunk
    })
    req.addListener('end', function () {
        xml2js.parseString(postdata, function (err, result) {
            if (!err) {
                onMsg(req, res, result.xml)
            }
        })
    })
})

var getToken = function () {
    request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appID + '&secret=' + appSecret,
        function (err, res, data) {
            console.log(data)
            var result = JSON.parse(data);
            accesstoken = result.access_token;
            console.log("access token " + accesstoken)
        });
    setTimeout(getToken, 1000 * 3600)
}

getToken()


var getUserInfo = function (userid, done) {
    request('https://api.weixin.qq.com/cgi-bin/user/info?access_token=' + accesstoken + '&openid=' + userid + '&lang=zh_CN',
        function (err, res, data) {
            var info = JSON.parse(data);
            done(info)
        });
}


var replyTmpl = '<xml>' +
    '<ToUserName><![CDATA[{toUser}]]></ToUserName>' +
    '<FromUserName><![CDATA[{fromUser}]]></FromUserName>' +
    '<CreateTime><![CDATA[{time}]]></CreateTime>' +
    '<MsgType><![CDATA[{type}]]></MsgType>' +
    '<Content><![CDATA[{content}]]></Content>' +
    '</xml>';
var replyImage = '<xml>' +
    '<ToUserName><![CDATA[{toUser}]]></ToUserName>' +
    '<FromUserName><![CDATA[{fromUser}]]></FromUserName>' +
    '<CreateTime><![CDATA[{time}]]></CreateTime>' +
    '<MsgType><![CDATA[{type}]]></MsgType>' +
    '<Image><MediaId><![CDATA[{MediaId}]]></MediaId></Image>' +
    '</xml>';

var onMsg = function (req, res, msg) {
    if (msg.MsgType == 'image') {
        var rmesg = tmpl(replyImage, {
            toUser: msg.FromUserName[0],
            fromUser: msg.ToUserName[0],
            type: 'image',
            time: Date.now(),
            MediaId: msg.MediaId
        })
        console.log(rmesg)
        res.end(rmesg)
    } else {
        var rmesg = tmpl(replyTmpl, {
            toUser: msg.FromUserName[0],
            fromUser: msg.ToUserName[0],
            type: 'text',
            time: Date.now(),
            content: "hello , i am yang xiao"
        })
        var userid = msg.FromUserName[0]
        var usertext = msg.Content
        getUserInfo(userid, function (info) {
            console.log(info)
            wss.broadcast(JSON.stringify({user: info, text: usertext}))
        })
        res.end(rmesg)
    }
}


module.exports = router

